#==================================================
#	Plugin
#==================================================
# 重写方法插件
#==================================================
# @path: res://addons/code_editor_menu_button/plugin/override/plugin.gd
# @datetime: 2021-7-4 22:24:14
#==================================================
class_name _CodeEditor_SubPlugin_OverrideMethod
extends _CodeEditor_SubPluginBase


const OverrideFunc = preload("OverrideFunc.tscn")


var override_func = OverrideFunc.instance()


#==================================================
#   自定义方法
#==================================================
#(override)
func install():
	.install()
	# OverrideFunc 节点
	override_func.connect("ok", self, "_on_OverrideFunc_ok")
	add_editor_node(override_func)
	override_func.editor_interface = get_editor_interface()


#(override)
func init_menu_button():
	.init_menu_button()
	# 添加菜单及设置其菜单快捷键
	_menu_button.set_item_shortcut(
		_menu_button.add_popup_item("重写方法", self, "override_method")
		, get_util() \
			.parse_shortcut_util \
			.parse_shortcut("Ctrl + Shift + O")
	)


#(override)
func uninstall():
	.uninstall()
	override_func.queue_free()


##  初始化方法数据
func override_method():
	var script = get_util().script_editor_util.get_current_script()
	# 显示方法列表
	override_func.show_method_list(script)
	# 显示弹窗
	override_func.popup_centered_ratio(0.5)


#==================================================
#   连接信号
#==================================================
func _on_OverrideFunc_ok(data_list: Array):
	var code = ""
	for data in data_list:
		code += """#(override)
func {name}({args}){return}:
	.{name}({s_args})

""".format({
	"name": data['name'],
	"args": _to_args(data['args']),
	"return": ((" -> " + data['return']) if data['return'] else ""),
	"s_args": _to_s_args(data['args'])
})
	
	# 插入代码
	var text_edit = get_util().script_editor_util.get_current_code_textedit()
	if text_edit:
		text_edit.insert_text_at_cursor(code.strip_edges())


func _to_args(args: Array):
	var code = ""
	for arg in args:
		if arg['type']:
			arg['type'] = ": " + arg['type']
		code += "{name}{type}, ".format(arg)
	return code.strip_edges().trim_suffix(",")


func _to_s_args(args: Array):
	var code = ""
	for arg in args:
		code += "{name}, ".format(arg)
	return code.strip_edges().trim_suffix(",")

